import axios from "axios";
import { Message } from "element-ui";
import { getcookie } from "@/utils/cookie";
import router from "@/router";
const url = process.env.NODE_ENV === "production" ? "/" : "/api";
const http = axios.create({
  baseURL: url,
  timeout: 5000
});

http.interceptors.request.use(
  config => {
    //请求拦截器
    if (getcookie()) {
      //做token验证的
      config.headers["token"] = getcookie();
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

http.interceptors.response.use(
  response => {
    //响应拦截器
    if (response.data.code == -1) {
      Message({
        message:
          response.data.message ||
          response.data.msg ||
          "token不存在，请重新登陆",
        type: "error"
      });
    }
    if (response.data.code == -2) {
      Message({
        message: response.data.data.error || "token不存在，请重新登陆",
        type: "error"
      });
      router.push("/");
    }
    return response;
  },
  error => {
    Message({
      message: error.message || "token不存在，请重新登陆",
      type: "error"
    });
    return Promise.reject(error);
  }
);

export default http;
